package thread.learn;

import java.util.concurrent.TimeUnit;

/*
 * 线程组： 把多个线程组合到一起。
 * 它可以对一批线程进行分类管理，Java 允许程序直接对线程组进行控制。
 *
 * 线程默认都是main线程组的
 *
 *
 */
public class ThreadGroupDemo {
    public static void main(String[] args) {
//        method1();
        method2();

        try {
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(" tg.interrupt();   可以中断整个组内的线程  ");
        tg.interrupt();
    }

    static ThreadGroup tg = new ThreadGroup("这是一个新的组");

    private static void method2() {
// ThreadGroup(String name)

        MyRunnable my = new MyRunnable();
// Thread(ThreadGroup group, Runnable target, String name)
        Thread t1 = new Thread(tg, my, "林青霞");
        Thread t2 = new Thread(tg, my, "刘意");
        System.out.println(t1.getThreadGroup().getName());
        System.out.println(t2.getThreadGroup().getName());
//通过组名称设置后台线程，表示该组的线程都是后台线程
        tg.setDaemon(true);
        t1.start();
        t2.start();
    }

    private static void method1() {
        MyRunnable my = new MyRunnable();
        Thread t1 = new Thread(my, "林青霞");
        Thread t2 = new Thread(my, "刘意");
// 我不知道他们属于那个线程组,我想知道，怎么办
// 线程类里面的方法：public final ThreadGroup getThreadGroup()
        ThreadGroup tg1 = t1.getThreadGroup();
        ThreadGroup tg2 = t2.getThreadGroup();
// 线程组里面的方法：public final String getName()
        String name1 = tg1.getName();
        String name2 = tg2.getName();
        System.out.println(name1);
        System.out.println(name2);
// 通过结果我们知道了：线程默认情况下属于 main 线程组
// 通过下面的测试，你应该能够看到，默任情况下，所有的线程都属于同一个组
        System.out.println(Thread.currentThread().getThreadGroup().getName());
    }
}

class MyRunnable implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
                Thread.currentThread().stop();
            }
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}